﻿using System;
using System.Diagnostics;
using System.Text;

namespace PhonePcFileTransfer
{
    public static class HotspotManager
    {
        /// <summary>
        /// 创建WiFi热点
        /// </summary>
        /// <param name="ssid">热点名称</param>
        /// <param name="password">热点密码（至少8位）</param>
        /// <returns>是否创建成功</returns>
        public static bool CreateHotspot(string ssid, string password)
        {
            if (string.IsNullOrEmpty(ssid) || string.IsNullOrEmpty(password) || password.Length < 8)
                throw new ArgumentException("热点名称不能为空，密码长度不能少于8位");

            try
            {
                // 首先停止可能正在运行的热点
                ExecuteCommand("netsh wlan stop hostednetwork");

                // 设置热点参数
                string setResult = ExecuteCommand($"netsh wlan set hostednetwork mode=allow ssid={ssid} key={password}");

                // 启动热点
                string startResult = ExecuteCommand("netsh wlan start hostednetwork");

                // 检查是否启动成功
                return startResult.Contains("已启动");
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 停止WiFi热点
        /// </summary>
        public static void StopHotspot()
        {
            try
            {
                ExecuteCommand("netsh wlan stop hostednetwork");
            }
            catch { }
        }

        /// <summary>
        /// 执行CMD命令
        /// </summary>
        private static string ExecuteCommand(string command)
        {
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    Arguments = $"/c {command}",
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    StandardOutputEncoding = Encoding.Default,
                    StandardErrorEncoding = Encoding.Default
                }
            };

            process.Start();
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();
            process.WaitForExit();

            if (!string.IsNullOrEmpty(error))
                throw new Exception(error);

            return output;
        }
    }
}
